﻿using UnityEngine;
using UnityEditor;
using System.Collections;

[CustomEditor(typeof(HCGrid))]
public class HCGridEditor : Editor {
	
	private const string _kGridArrayData = "_grid.Array.data[{0}]";
	private const string _kGridArraySize = "_grid.Array.size";
	
	private SerializedObject _object;
	private SerializedProperty _columns;
	private SerializedProperty _rows;
	private SerializedProperty _radius;
	private SerializedProperty _hexagonPrefab;
	private SerializedProperty _gridSize;
	
	SerializedProperty _emptyMaterial = null;
	
	SerializedProperty _blackMaterial = null;
	
	SerializedProperty _whiteMaterial = null;
	
	SerializedProperty _wildCardMaterial = null;
	
	SerializedProperty _solidMaterial = null;
	
	SerializedProperty _selectionMaterial = null;
	
	//private HCGrid _grid;
	private static bool _created;
	private bool _showCreationFold;
	
	private Transform[] _unitList;
	
	public void OnEnable()
	{
		_object = new SerializedObject(target);
		_columns = _object.FindProperty("_columns");
		_rows = _object.FindProperty("_rows");
		_radius = _object.FindProperty("_hexaRadius");
		_hexagonPrefab = _object.FindProperty("_hexagonPrefab");
		_gridSize = _object.FindProperty( _kGridArraySize );
		
		_emptyMaterial = _object.FindProperty("_emptyMaterial");
		_blackMaterial = _object.FindProperty("_blackMaterial");
		_whiteMaterial = _object.FindProperty("_whiteMaterial");
		_wildCardMaterial = _object.FindProperty("_wildCardMaterial");
		_solidMaterial = _object.FindProperty("_solidMaterial");
		_selectionMaterial = _object.FindProperty("_selectionMaterial");
		
		_created = _gridSize.intValue > 0;
		_showCreationFold = false;
		Debug.Log("OnEnable");
	}

	public override void OnInspectorGUI()
	{
		//DrawDefaultInspector();
		_object.Update();
		
		EditorGUILayout.PropertyField( _columns );
		EditorGUILayout.PropertyField( _rows );
		EditorGUILayout.PropertyField( _radius );
		EditorGUILayout.PropertyField( _hexagonPrefab );
		
		EditorGUILayout.PropertyField( _emptyMaterial );
		EditorGUILayout.PropertyField( _blackMaterial );
		EditorGUILayout.PropertyField( _whiteMaterial );
		EditorGUILayout.PropertyField( _wildCardMaterial );
		EditorGUILayout.PropertyField( _solidMaterial );
		EditorGUILayout.PropertyField( _selectionMaterial );
		
		_showCreationFold = EditorGUILayout.Foldout(_showCreationFold, "Create");
		if(_showCreationFold)
		{
			GUILayout.Space(10f);
			GUILayout.Label("Generation");
			
			var oldEnabled = GUI.enabled;
			GUI.enabled = !_created;
			
			EditorGUILayout.BeginHorizontal();
			
			if( GUILayout.Button("Generate") )
			{
				CreateGrid();
			}
			
			GUI.enabled = _created;
			if( GUILayout.Button("Destroy", GUILayout.Width( 80f ) ) )
			{
				DestroyGrid();
			}
	
			GUI.enabled = oldEnabled;
			
			EditorGUILayout.EndHorizontal();
			
			GUILayout.Space(10f);
		}
		
		_object.ApplyModifiedProperties();
		
	}
	
	private HCHexagonController[] GetGridArray()
	{
		var _count = _gridSize.intValue;
		var _hexArray = new HCHexagonController[_count];
		
		for( int i = 0; i < _count; i++ )
			_hexArray[i] = _object.FindProperty( string.Format(_kGridArrayData,i) ).objectReferenceValue as HCHexagonController;
		
		return _hexArray;
	}
	
	private void SetTile( int _idx, HCHexagonController _tile )
	{
		_object.FindProperty( string.Format(_kGridArrayData, _idx) ).objectReferenceValue = _tile;
	} 
	
	private HCHexagonController GetTile( int _idx )
	{
		return _object.FindProperty( string.Format(_kGridArrayData, _idx) ).objectReferenceValue as HCHexagonController;
	} 
	
	private void RemoveTile( int _idx )
	{
		var _tile = _object.FindProperty( string.Format(_kGridArrayData, _idx) ).objectReferenceValue as HCHexagonController;
		//Undo.RecordObject(_tile, "remove");
		if( null != _tile )
		{
			DestroyImmediate( _tile.gameObject );
			//EditorUtility.SetDirty(_tile);
			_tile = null;
		}
	}
	
	private void CreateGrid()
	{
		float _s = 1.5f * _radius.floatValue;
		float _h = Mathf.Sqrt( 3f ) * _radius.floatValue;
		
		HCGrid _grid = (_object.targetObject as HCGrid);
		for( int j = 0; j < _rows.intValue; j++ )
		{
			for( int i = 0; i < _columns.intValue; i++ )
			{
				
				Transform _hexTfrm = Instantiate( _hexagonPrefab.objectReferenceValue, Vector3.zero, Quaternion.identity ) as Transform;
				HCHexagon _hexView = _hexTfrm.GetComponent<HCHexagon>();
				HCHexagonController _hexController = _hexTfrm.GetComponent<HCHexagonController>();
				_hexController.Grid = _grid;
				_hexController.Row = j;
				_hexController.Column = i;
				_hexController.View = _hexView;
				_hexView.renderer.material = _hexController.Grid.EmptyMaterial;
				
				_hexView.Radius = _radius.floatValue;
				_hexView.transform.parent = _hexController.Grid.transform;
				_hexView.transform.localPosition = new Vector3( (float)i * _s + _radius.floatValue, 0.0f, (float)j * _h + (i % 2) * _h * 0.5f + _h * 0.5f);
				_gridSize.intValue++; 
				SetTile( j * _columns.intValue + i, _hexController );
			}
		}
		
		HCHexagonController[] _gridArray = GetGridArray();
		/*
		for( int i = 0; i < _gridArray.Length; i++ )
		{
			_gridArray[i].Neighborhood = _grid.GetNearHexagon( _gridArray[i] );
		}
		*/
		
		_created = true;
		CreateCollider();
	}
	
	private void DestroyGrid()
	{
		int _size = _gridSize.intValue;
		for( int i = _size - 1; i >= 0; i-- )
		{
			RemoveTile( i );
			_gridSize.intValue--;
		}
		
		_created = false;
		
		MeshCollider _meshCollider = ((HCGrid)(_object.targetObject)).GetComponent<MeshCollider>();
		_meshCollider.sharedMesh = null;
	}
	
	public void CreateCollider()
	{
		// create hexagon polygon
		Vector3[] _vertices = new Vector3[4];
		int[] _triangles = new int[6]{ 0,2,1, 1,2,3 };
		
		float _s = _radius.floatValue*(3f*_columns.intValue+1)*0.5f;
		float _h = Mathf.Sqrt( 3f ) * _radius.floatValue;
		for( int v = 0; v < 4; v++ )
		{
			_vertices[v] = new Vector3( (v%2)*_s, 0.0f, Mathf.Floor(v * 0.5f) * ( (float)_rows.intValue + 0.5f) * _h );
		}
		
		Mesh _mesh = new Mesh();
		_mesh.vertices = _vertices;
		_mesh.triangles = _triangles;
		
		//MeshFilter _mf = GetComponent<MeshFilter>();
		//_mf.mesh = _mesh;
		_mesh.name = "Grid";
		MeshCollider _meshCollider = ((HCGrid)(_object.targetObject)).GetComponent<MeshCollider>();
		_meshCollider.sharedMesh = _mesh;
	}
	
}
